package com.neusoft.heart.rate.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.neusoft.heart.rate.DataBaseUtil.CommonUtils;
import com.neusoft.heart.rate.R;
import com.neusoft.heart.rate.adapter.MyWheelAdapter;
import com.neusoft.heart.rate.bean.News;
import com.neusoft.heart.rate.bean.NewsAdapter;
import com.neusoft.heart.rate.bean.WGoods;
import com.neusoft.heart.rate.bean.WGoodsAdapter;
import com.neusoft.heart.rate.util.BottomDialog;
import com.neusoft.heart.rate.util.ToastUtil;
import com.wx.wheelview.widget.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;

import org.apache.commons.collections.functors.StringValueTransformer;

public class RecyclerView extends AppCompatActivity {
    private android.support.v7.widget.RecyclerView  recycler_view;
    private Button bten;
    private BottomDialog bottomDialog;
    private static final String TAG = "RecyclerView";


    private EditText text;

    private Calendar cal;
    private int year,month,day;








    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_recycler_view);//R.layout.activity_recycler_view
      //  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      //  setSupportActionBar(toolbar);


        cal=Calendar.getInstance(Locale.CHINA);

        Date myDate=new Date();
        cal.setTime(myDate);

        year=cal.get(Calendar.YEAR);       //获取年月日时分秒
        Log.i("wxy","year"+year);
        month=cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day=cal.get(Calendar.DAY_OF_MONTH);



        text =(EditText)findViewById(R.id.editText4);
        text.setCursorVisible(false);
        text.setFocusable(false);
        text.setFocusableInTouchMode(false);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getId()==R.id.editText4){

                    dialogtime();

                  /*  OnDateSetListener listener=new OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker arg0, int year, int month, int day) {

                            String days;
                            if (month + 1 < 10) {
                                if (day < 10) {
                                    days = new StringBuffer().append(year).append("年").append("0").
                                            append(month + 1).append("月").append("0").append(day).append("日").toString();
                                } else {
                                    days = new StringBuffer().append(year).append("年").append("0").
                                            append(month + 1).append("月").append(day).append("日").toString();
                                }

                            } else {
                                if (day < 10) {
                                    days = new StringBuffer().append(year).append("年").
                                            append(month + 1).append("月").append("0").append(day).append("日").toString();
                                } else {
                                    days = new StringBuffer().append(year).append("年").
                                            append(month + 1).append("月").append(day).append("日").toString();
                                }

                            }

                            text.setText(days);
                            //text.setText(year+"-"+(++month)+"-"+day);      //将选择的日期显示到TextView中,因为之前获取month直接使用，所以不需要+1，这个地方需要显示，所以+1
                        }
                    };//THEME_HOLO_LIGHT  DatePickerDialog.THEME_HOLO_LIGHT AlertDialog.THEME_HOLO_DARK,
                    DatePickerDialog dialog=new DatePickerDialog(RecyclerView.this,AlertDialog.THEME_HOLO_DARK,listener,year,month,day);//主题在这里！后边三个参数为显示dialog时默认的日期，月份从0开始，0-11对应1-12个月
                    dialog.getDatePicker().setCalendarViewShown(false);

                    dialog.show();

                     */
                }
            }
        });









     /*   for (int i=0;i<=10;i++)//添加数据
        {
            News news =new News("https://weixin.fxsoft88.com/WeeSee_images/goodsimg/2018-03-19-15-113363.jpg","这是一条新闻"+String.valueOf(i),"伏羲软件","2018-12-27","www.fuxi.com");

            dataItems.add(news);


        } */



        GetGoods a=   new GetGoods("http://192.168.1.25:8080/testmybatis/syndata/syntools.do?");//.execute("查询货品数据");
        a.execute();
        a.setOnDataFinishedListener(new OnDataFinishedListener() {
            @Override
            public void onDataSuccessfully(String data) {

                List<WGoods> dataItems=JSON.parseArray(data,WGoods.class);
                recycler_view =(android.support.v7.widget.RecyclerView)findViewById(R.id.recycler_view);
                //  recycler_view.getLayoutManager();
                recycler_view.setLayoutManager(new LinearLayoutManager(RecyclerView.this));
                //   NewsAdapter  adapter =new NewsAdapter();

                System.out.println("输出list:"+dataItems);
                WGoodsAdapter adapter=new WGoodsAdapter();


                adapter.setDataItems(dataItems);

                recycler_view.setAdapter(adapter);

                adapter.setOnItemClickListener(new WGoodsAdapter.OnItemClickListener() {
                    //这个是点击事件
                    @Override
                    public void onClick(List<WGoods> dataItems,int position) {
                     //   List<WGoods> dataItems=(List<WGoods>) recycler_view.getAdapter().;


                        //    WGoods g=(WGoods)dataItems.get(position);
                        System.out.println(((WGoods)dataItems.get(position)).getCode());
                                //recycler_view.getAdapter().getItemId(position);
                    }
                    //这个是长按事件
                    @Override
                    public void onLongClick(List<WGoods> dataItems,int position) {

                    }
                });





            }

            @Override
            public void onDataFailed() {
                Toast.makeText(RecyclerView.this, "加载失败！", Toast.LENGTH_SHORT).show();
            }
        });



       // recycler_view.setAdapter(adapter);

   /*
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });  */

    }

public void init(String data){




}

    public class GetGoods extends AsyncTask<String, Void, String> {
        //上面的方法中，第一个参数：网络图片的路径，第二个参数的包装类：进度的刻度，第三个参数：任务执行的返回结果

        String mUrl;
        OnDataFinishedListener onDataFinishedListener;

        public GetGoods(String url){
            this.mUrl = url;
        }

        public void setOnDataFinishedListener(OnDataFinishedListener onDataFinishedListener) {
            this.onDataFinishedListener = onDataFinishedListener;
        }





        @Override
        //在界面上显示进度条
        protected void onPreExecute() {
            // dialog.show() ;
        };
        protected String doInBackground(String... params) {  //三个点，代表可变参数
            // HttpClient httpClient = new DefaultHttpClient() ;
            //            HttpGet httpget = new HttpGet(params[0]) ;
            String datastr =null;
            try {

              datastr= CommonUtils.httpRequest(mUrl,"POST","currpage=1&pagesize=10&field=GoodsID,Code,GoodName,Imgpath&tbl=W_Goods&keyid=GoodsID");

               // net.sf.json.JSONObject json=    net.sf.json.JSONObject.fromObject(datastr);


             //  datastr =json.get("ls").toString();
             //   List<WGoods> l =  JSON.parseArray(json.get("ls").toString(),WGoods.class);


             //   return l;

            }  catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          return   datastr;
        }
        //主要是更新UI
        @Override
        protected void onPostExecute( String result) {
            super.onPostExecute(result);
            //imageView.setImageBitmap(result) ;//更新UI
            //dialog.dismiss() ;

            System.out.println("拿到值："+result);
            //net.sf.json.JSONObject  json= net.sf.json.JSONObject.fromObject(result)  ;


            if(result!=null){
                onDataFinishedListener.onDataSuccessfully(result);
            }else{
                onDataFinishedListener.onDataFailed();
            }





        }
    }
    //  回调接口：
    public interface OnDataFinishedListener {

        public void onDataSuccessfully(String  data);

        public void onDataFailed();

    }

    private void dialogtime() {
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextColor = Color.parseColor("#1A1A1A");//选中字体颜色
        style.textColor = Color.parseColor("#ABABAB");//未选中字体颜色


        View out_view = LayoutInflater.from(RecyclerView.this).inflate(R.layout.dialog_time, null);
        //日期滚轮
        final WheelView start_year =(WheelView) out_view.findViewById(R.id.start_year);
        final WheelView start_month =(WheelView) out_view.findViewById(R.id.start_month);
        final WheelView start_day = (WheelView)out_view.findViewById(R.id.start_day);
        final WheelView end_year =(WheelView) out_view.findViewById(R.id.end_year);
        final WheelView end_month = (WheelView)out_view.findViewById(R.id.end_month);
        final WheelView end_day =(WheelView) out_view.findViewById(R.id.end_day);
        TextView tv_ok = (TextView)out_view.findViewById(R.id.tv_ok);
        TextView tv_cancel =(TextView) out_view.findViewById(R.id.tv_cancel);
        start_year.setStyle(style);
        start_month.setStyle(style);
        start_day.setStyle(style);
        end_year.setStyle(style);
        end_month.setStyle(style);
        end_day.setStyle(style);

        // 格式化当前时间，并转换为年月日整型数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String[] split = sdf.format(new Date()).split("-");
        int currentYear = Integer.parseInt(split[0]);
        int currentMonth = Integer.parseInt(split[1]);
        int currentDay = Integer.parseInt(split[2]);
        //开始时间
        start_year.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        start_year.setWheelData(getYearData(currentYear));
        start_year.setSelection(0);
        start_month.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        start_month.setWheelData(getMonthData());
        start_month.setSelection(currentMonth - 1);
        start_day.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        start_day.setWheelData(getDayData(getLastDay(currentYear, currentMonth)));
        start_day.setSelection(currentDay - 1);
        //结束时间
        end_year.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        end_year.setWheelData(getYearData(currentYear));
        end_year.setSelection(0);
        end_month.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        end_month.setWheelData(getMonthData());
        end_month.setSelection(currentMonth - 1);
        end_day.setWheelAdapter(new MyWheelAdapter(RecyclerView.this));
        end_day.setWheelData(getDayData(getLastDay(currentYear, currentMonth)));
        end_day.setSelection(currentDay - 1);


        //确定
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
                String start_time;
                String end_time;
                Object startyear1 = start_year.getSelectionItem();
                Object startmonth1 = start_month.getSelectionItem();
                Object startday1 = start_day.getSelectionItem();
                Object endyear1 = end_year.getSelectionItem();
                Object endmonth1 = end_month.getSelectionItem();
                Object endday1 = end_day.getSelectionItem();
                int startyear = Integer.valueOf(String.valueOf(startyear1));
                int startmonth = Integer.valueOf(String.valueOf(startmonth1));
                int startday = Integer.valueOf(String.valueOf(startday1));
                String startmonth2;
                if (startmonth < 10) {
                    startmonth2 = "0" + String.valueOf(+startmonth);
                } else {
                    startmonth2 = String.valueOf(startmonth);
                }
                String startday2;
                if (startday < 10) {
                    startday2 = "0" + String.valueOf(startday);
                } else {
                    startday2 = String.valueOf(startday);
                }
                int endyear = Integer.valueOf(String.valueOf(endyear1));
                int endmonth = Integer.valueOf(String.valueOf(endmonth1));
                int endday = Integer.valueOf(String.valueOf(endday1));
                String endmonth2;
                if (endmonth < 10) {
                    endmonth2 = "0" + String.valueOf(endmonth);
                } else {
                    endmonth2 = String.valueOf(endmonth);
                }
                String endday2;
                if (endday < 10) {
                    endday2 = "0" + String.valueOf(endday);
                } else {
                    endday2 = String.valueOf(endday);
                }

                if (endyear - startyear == 0) {
                    if (endmonth - startmonth <= 2 && endmonth - startmonth >= 0) {
                        if (endmonth - startmonth == 0) {
                            if (endday - startday >= 0) {
                                start_time = startyear + "/" + startmonth2 + "/" + startday2;

                                end_time = endyear + "/" + endmonth2 + "/" + endday2;

                                Log.e(TAG, "starttime: " + start_time + "/n" + "endtime:" + end_time);

                                text.setText(end_time);

                            } else {
                                ToastUtil.showToast(RecyclerView.this, "当月起始日期不能大于结束日期");
                            }
                        } else {
                            start_time = startyear + "/" + startmonth2 + "/" + startday2;

                            end_time = endyear + "/" + endmonth2 + "/" + endday2;

                            Log.e(TAG, "starttime: " + start_time + "/n" + "endtime:" + end_time);

                        }
                    } else if (endmonth < startmonth) {
                        ToastUtil.showToast(RecyclerView.this, "起始时间不能大于结束时间");
                    } else {
                        ToastUtil.showToast(RecyclerView.this, "请选择两个月");
                    }
                } else {
                    ToastUtil.showToast(RecyclerView.this, "请输入正确的年份");
                }
            }
        });
        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        //防止弹出两个窗口
        if (bottomDialog != null && bottomDialog.isShowing()) {
            return;
        }
        bottomDialog = new BottomDialog(RecyclerView.this, R.style.ActionSheetDialogStyle);
        //将布局设置给Dialog
        bottomDialog.setContentView(out_view);
        bottomDialog.show();//显示对话框

    }

    //设置年
    private ArrayList<String> getYearData(int currentYear) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = currentYear; i >= 1900; i--) {
            list.add(String.valueOf(i));
        }
        return list;
    }


    //月
    private ArrayList<String> getMonthData() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            list.add(String.valueOf(i));
        }
        return list;
    }

    //日
    private ArrayList<String> getDayData(int lastDay) {
        //ignore condition
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i <= lastDay; i++) {
            list.add(String.valueOf(i));
        }
        return list;
    }

    /**
     * 判断是否闰年
     *
     * @param year
     * @return
     */
    private boolean isLeapYear(int year) {
        return (year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
    }

    /**
     * 获取特定年月对应的天数
     *
     * @param year
     * @param month
     * @return
     */
    private int getLastDay(int year, int month) {
        if (month == 2) {
            // 2月闰年的话返回29，防止28
            return isLeapYear(year) ? 29 : 28;
        }
        // 一三五七八十腊，三十一天永不差
        return month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ? 31 : 30;
    }







}

